package com.kehutong.common.excel.tool;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.kehutong.common.errcode.Assert;
import com.kehutong.common.excel.config.StyleConfig;
import com.kehutong.common.excel.converter.LocalDateConverter;
import com.kehutong.common.excel.converter.TimestampConverter;
import com.kehutong.common.excel.entity.ImportResult;
import com.kehutong.common.excel.listener.BindTransfer;
import com.kehutong.common.excel.listener.ExcelImportListener;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.ListUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.coraframework.http.HttpHeaders;
import org.coraframework.inject.Inject;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.function.Function;


/**
 * Excel 工具（请注意看具体备注内容）
 * @author jian Ye
 * @Date 2021/7/30
 **/
@Singleton
@SuppressWarnings("unchecked")
public class ExcelTool {

    private static final Logger log = LoggerFactory.getLogger(ExcelTool.class);

    public static final int MAX_ROWS = 999999;
    private static final String[] FILE_ID = {"id","fileId"};
    private static final String SUCCESS_MSG = "数据导入成功!导入%s条,成功%s条";


    @Inject
    private FileUrlConfig fileUrlConfig;

    /**
     * 导入成功后提示结果
     *
     * @Param importSize   导入的总数
     * @Param successCount 成功的条数
     * @author jian Ye
     * @Date 2021/7/30
     **/
    public static String importSuccessResult(Integer importSize, Integer successCount) {
        return String.format(SUCCESS_MSG, importSize, successCount);
    }


    public static ImportResult R(Integer importTotal, Integer successTotal, String errorMsg) {
        return new ImportResult(importTotal,successTotal,errorMsg);
    }



    /**
     * 导入Excel 【注意由于模板限制，在本项目中都是从第二行获取表头信息】
     *
     * @return 成功->返回list； 中途失败->会全量清空数据。如果使用了Validation参数校验，会抛出具体行号异常（ExcelAnalysisException）
     * @Param file 导入的文件
     * @Param tClass 导入的数据类型 (实体类字段必须注解 @ExcelProperty(value = "excel字段名称"))
     * @author jian Ye
     * @Date 2021/7/30
     **/
    public <T> List<T> excelImport(JSONObject flag, Class<T> tClass) {
        String fileId = Objects.isBlank(flag.getString(FILE_ID[0]))?flag.getString(FILE_ID[1]):flag.getString(FILE_ID[0]);
        InputStream fileStream;
        try {
            fileStream = fileUrlConfig.download(fileId);
        } catch (Exception e) {
            throw new RuntimeException("文件获取失败，请联系管理员(FILE_DOWNLOAD_ERROR).");
        }
        Assert.mustTrue(isExcelFile(fileStream), "文件类型不匹配");
        //magic by poi responsible for checking
        ExcelImportListener listener = new ExcelImportListener(tClass);
        EasyExcel.read(fileStream, tClass, listener)
                .registerConverter(new LocalDateConverter())
                .registerConverter(new TimestampConverter())
                .headRowNumber(2).sheet().doRead();
        List<T> list = listener.getList();
        if(Objects.isEmpty(list)){
            String error = BindTransfer.castFieldName(tClass);
            throw new ExcelAnalysisException(error);
        }
        return list;
    }

    /**
     * 导出excel
     * 导出类型：xlsx
     *
     * @Param data 需要导出的数据
     * @Param fileName 导出的文件名(Windows文件名特殊符号仅支持下划线)
     * @author jian Ye
     * @Date 2021/7/30
     **/
    public <T> void excelDownload(HttpServletRequest req, HttpServletResponse resp, List<T> data, String fileName) {
        ExcelWriter excelWriter = null;
        Assert.notEmpty(data, "Excel导出失败,没有找到相关数据");
        try {
            long exportStartTime = System.currentTimeMillis();
            Class<?> aClass = data.get(0).getClass();
            List<List<T>> lists = ListUtils.splitList(data, MAX_ROWS);
            OutputStream out = getOutputStream(fileName, resp);
            ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(out, aClass)
                    .excelType(ExcelTypeEnum.XLSX).registerWriteHandler(StyleConfig.headStyle());
            excelWriter = excelWriterBuilder.build();
            ExcelWriterSheetBuilder excelWriterSheetBuilder;
            WriteSheet writeSheet;
            for (int i = 1; i <= lists.size(); i++) {
                excelWriterSheetBuilder = new ExcelWriterSheetBuilder(excelWriter);
                excelWriterSheetBuilder.sheetNo(i);
                excelWriterSheetBuilder.sheetName(fileName + i);
                writeSheet = excelWriterSheetBuilder
                        .registerConverter(new LocalDateConverter())
                        .registerConverter(new TimestampConverter())
                        .build();
                excelWriter.write(lists.get(i - 1), writeSheet);
            }
            log.debug("[Excel导出]请求: {} 导出耗时: {}ms", req.getRequestURI(), System.currentTimeMillis() - exportStartTime);
        } catch (IOException e) {
            log.error("[Excel导出]导出失败", e);
            throw new RuntimeException("Excel导出失败(DOWNLOAD_IO_ERROR)");
        } finally {
            if (null != excelWriter) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 导出excel
     * 导出类型：xlsx
     *
     * @param resp
     * @param function
     * @Param req
     * @Param fileName 导出的文件名(Windows文件名特殊符号仅支持下划线)
     **/
    public <R> void excelDownload(HttpServletRequest req, HttpServletResponse resp, String fileName, Function<ExcelWriter, R> function) {
        ExcelWriter excelWriter = null;
        try {
            long exportStartTime = System.currentTimeMillis();
            OutputStream out = getOutputStream(fileName, resp);
            ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory
                    .write(out)
                    .excelType(ExcelTypeEnum.XLSX)
                    .needHead(true)
                    .registerWriteHandler(StyleConfig.headStyle());
            excelWriter = excelWriterBuilder
                    .registerConverter(new LocalDateConverter())
                    .registerConverter(new TimestampConverter())
                    .build();

            R rowNum = function.apply(excelWriter);

            log.info("[Excel导出]请求:{}, 行数：{}, 导出耗时: {}ms", req.getRequestURI(), rowNum, System.currentTimeMillis() - exportStartTime);
        } catch (IOException e) {
            log.error("[Excel导出]导出失败", e);
            throw new RuntimeException("Excel导出失败(DOWNLOAD_IO_ERROR)");
        } finally {
            if (null != excelWriter) {
                excelWriter.finish();
            }
        }
    }




    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws IOException {
        String formatDate = DateUtils.formatDate(new Date(), "yyyyMMddHHmm");
        fileName = fileName + "_" + formatDate + ".xlsx";
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
        return response.getOutputStream();
    }

    private static Boolean isExcelFile(InputStream inputStream) {
        try {
            FileMagic fileMagic = FileMagic.valueOf(inputStream);
            if (FileMagic.OLE2.equals(fileMagic) || FileMagic.OOXML.equals(fileMagic)) {
                return true;
            }
        } catch (IOException e) {
            log.error("[Excel导入]校验导入文件IO（魔数）异常！", e);
            return false;
        }
        return false;
    }


}